<template>
  <div>
    <div>
      <el-form :model="formData">
        <el-row>
          <el-col :span="6">
            <el-form-item label="类别:">
              <el-tree-select v-model="menu.categoryId" :props="{ value: 'id', label: 'name', children: 'children' }"
                :data="organTreeData" :render-after-expand="false" check-strictly clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键词:">
              <el-input v-model="menu.keyword" placeholder="请输入条码、名称、规格、型号查询"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="颜色:">
              <el-input v-model="menu.color" placeholder="请输入颜色查询"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="search">查 询</el-button>
              <el-button @click="reset" style="margin-left: 8px;">重 置</el-button>
              <span @click="toggleSearch" style=" cursor: pointer;margin-left: 8px;color: #1890FF;font-size: 14px; ">
                {{ isSearchVisible ? '收起' : '展开' }}
                <el-icon>
                  <ArrowDown v-if="!isSearchVisible" />
                  <ArrowUp v-else />
                </el-icon>
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="状态:">
              <el-select v-model="menu.enabled">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="序列号:">
              <el-select>
                <el-option label="有" value="1"></el-option>
                <el-option label="无" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="批号:">
              <el-select>
                <el-option label="有" value="1"></el-option>
                <el-option label="无" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="仓库货架:">
              <el-input v-model="menu.position" placeholder="请输入仓库货架查询"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="扩展信息:">
              <el-input v-model="menu.mfrs" placeholder="请输入扩展信息查询"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="基础重量:">
              <el-input v-model="menu.weight" placeholder="请输入基础重量查询"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="保质期:">
              <el-input v-model="menu.expiryNum" placeholder="请输入保质期查询"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="isSearchVisible">
            <el-form-item label="备注:">
              <el-input v-model="menu.remark" placeholder="请输入备注查询"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="table-operator" style="margin-top: 5px;">
      <el-button type="primary" v-perm:commodity:material:insert="insert"><el-icon>
          <Plus fill="currentColor" />
        </el-icon>新增</el-button>
      <el-button type="primary" @click="exportBtn" ><el-icon>
          <Plus fill="currentColor" />
        </el-icon>导出</el-button>
      <!-- <el-button type="primary"><el-icon>
          <Plus fill="currentColor" />
        </el-icon>导出</el-button> -->
      <!-- 批量操作 -->
      <el-dropdown>
        <el-button class="ant-btn" style="margin-left: 8px;">
          批量操作<el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <template v-for="item in strBtn">
              <template v-if="item === '编辑'">
                <el-dropdown-item @click="removes">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  <span>删除</span>
                </el-dropdown-item>
              </template>
              <template v-else-if="item === '审核'">
                <el-dropdown-item @click="modifyTheState(1)">
                  <el-icon>
                    <Select />
                  </el-icon>
                  <span> 启用 </span>
                </el-dropdown-item>
              </template>
              <template v-else>
                <el-dropdown-item @click="modifyTheState(0)">
                  <el-icon>
                    <CircleClose />
                  </el-icon>
                  <span> 禁用 </span>
                </el-dropdown-item>
              </template>

                </template>

              </el-dropdown-menu>
            </template>
          </el-dropdown>


      <el-popover placement="right" width="400" trigger="click">
        <el-checkbox-group v-model="visibleColumns" style="display: flex; flex-wrap: wrap;">
          <el-checkbox v-for="column in columns" :key="column.prop" :label="column.prop"
            style="flex: 1 1 25%; margin-bottom: 10px; box-sizing: border-box;">
            {{ column.label }}
          </el-checkbox>
        </el-checkbox-group>
        <template #reference>
          <el-button style="margin-left: 8px;">
            <el-icon>
              <Setting />
            </el-icon>
            列设置
          </el-button>
        </template>
      </el-popover>

    </div>
    <div style="margin-top: 10px;  width: 100%; ">
      <div>
        <el-table ref="tableRef" v-if="columns.length > 0" v-loading="loading" :data="page.records" :selected-rows="selectedProducts"
          @selection-change="handleSelectionChange" style="width: 100%; height: 400px;" border>
          <el-table-column width="50" type="selection"></el-table-column>
          <template v-for="column in columns" :key="column.prop">
            <el-table-column v-if="column.visible" :prop="column.prop" :label="column.label" :width="column.width"
              :align="column.align">
              <template #default="scope" v-if="column.prop === 'operation'">
                <div style="display: flex; align-items: center;">
                  <el-button type="text" size="small" v-perm:commodity:material:update="update"
                    :row="scope.row">编辑</el-button>

                  <el-popconfirm title="确认删除该项吗？" @confirm="remove(scope.row)">
                    <template #reference>
                      <el-button v-perm:commodity:material:remove type="text" size="small">删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
              <template #default="{ row }" v-if="column.prop === 'unit'">
                {{ row.unit || row.erpUnit.name }}
              </template>
              <template #default="scope" v-if="column.prop === 'enabled'">
                <el-tag v-if="scope.row.enabled == 0" type="danger">禁用</el-tag>
                <el-tag v-else-if="scope.row.enabled == 1" type="success">启用</el-tag>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>

      <div style="display: flex; justify-content: flex-end; margin-top: 40px; margin-bottom: 50px;">
        <el-pagination v-model:page-size="page.size" v-model:current-page="page.current"
          @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="page.total" background>
        </el-pagination>
      </div>
    </div>
    <div>
      <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="1400px">
        <router-view @close="close" :data="data"></router-view>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, defineProps } from 'vue';
import reqeust from '@/api/request'
import router from '@/router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { exportTable } from '@/utils/xlsx'
import { ArrowDown, ArrowUp, Edit, Setting } from '@element-plus/icons-vue'; // 根据你的项目配置引入图标
const props = defineProps(['strBtn'])
let tableRef = ref(null);


const exportBtn = () => {
exportTable(tableRef, '商品列表')
}


// 弹窗
let visible = ref(false);
let title = ref("");
let data = ref({});

let selectedProducts = ref([]);

// 定义响应式变量来控制搜索框显示
const loading = ref(false)
const isSearchVisible = ref(false);

// 切换搜索框显示状态的函数
const toggleSearch = () => {
  isSearchVisible.value = !isSearchVisible.value;
};

let currentBarcode = ref('');



// 重置方法
const reset = () => {
  menu.value = {}; // 清空查询条件
  loadMenus(); // 重新加载数据
}


//分页查询
const page = ref({
  current: 1,
  size: 10,
  total: 0,
  records: []
});
let menu = ref({})



const handleSelectionChange = (val) => {
  selectedProducts.value = val; // 更新选中的行
  console.log('ddd', selectedProducts.value);
};




console.log('page:', page.value);







const handleSizeChange = (val) => {
  page.value.size = val; // 更新每页条数
  page.value.current = 1; // 重置为第一页
  loadMenus(); // 重新加载数据
};
const handleCurrentChange = (val) => {
  page.value.current = val; // 更新当前页码
  loadMenus(); // 重新加载数据
};

// 加载类别数据
const organTreeData = ref([]);
const findOrgan = () => {
  reqeust.get('cam/findOrganTree').then(resp => {
    if (resp.code == 200) {
      organTreeData.value = resp.data
    }
  })
}
findOrgan();



// 修改 loadMenus 函数，确保传入当前页和每页大小
let loadMenus = (params = {}) => {
  loading.value = true; // 请求开始，设置加载状态为 true

  const queryParams = {
    current: page.value.current,
    size: page.value.size,
    ...params // 展开其它的查询参数
  };

  reqeust({
    url: '/commodity/material/findByPage',
    method: "get",
    params: queryParams // 使用构建的请求参数
  }).then(res => {
    console.log('缇娜 ', res.data);
    // 检查响应数据是否有效
    if (res && res.data) {

      page.value = {
        ...page.value,
        total: res.data.total, // 更新总条目数
        records: res.data.records // 更新当前页面的记录
      };


    }
  }).finally(() => {
    loading.value = false; // 请求结束，设置加载状态为 false
  });
};

// 修改 search 函数以保留分页信息
const search = () => {
  const params = {
    categoryId: menu.value.categoryId,
    keyword: menu.value.keyword,
    color: menu.value.color,
    position: menu.value.position,
    mfrs: menu.value.mfrs,
    weight: menu.value.weight,
    expiryNum: menu.value.expiryNum,
    remark: menu.value.remark,
    enabled: menu.value.enabled
  };
  loadMenus(params); // 保留分页信息
};
loadMenus();
onMounted(() => {
  // 监听路由变化，刷新页面
  // router.afterEach(() => {
  //   loadMenus(); // 重新加载数据
  // });
});

const remove = async (row) => {
  // try {
  console.log('删除单个商品', row.id);

  // 检查商品是否被引用
  await reqeust.get(`/commodity/material/checkIfUsed/${row.id}`).then(resp => {
    console.log(resp);
    if (resp.data > 0) {
      ElMessage.warning("检测到存在依赖数据，不能删除!");
    } if (resp.data == 0 || resp.data == null) {
      reqeust.delete(`/commodity/material/delete/${row.id}`).then(resp => {
        if (resp.code == 200) {
          ElMessage.success('删除成功！');
        }
        else {
          ElMessage.error('删除失败，请重试。');
        }
        loadMenus(); // 重新加载数据

      })
    }
  })

};

// 批量删除
let removes = async () => {
  const ids = selectedProducts.value.map(item => item.id); // 从选中的商品中获取 ID
  console.log('批量删除', ids);

  if (ids.length === 0) {
    ElMessage.warning('请先选择要删除的商品！'); // 如果没有选择，提示用户
    return;
  }

  // 存储检查结果
  let canDelete = true;
  let message = '';

  // 检查每个商品是否被引用
  for (let id of ids) {
    const response = await reqeust.get(`/commodity/material/checkIfUsed/${id}`); // 检查商品使用状态
    if (response.code === 200) {
      if (response.data > 0) { // 如果引用计数大于 0
        canDelete = false; // 标记为无法删除
        message = `检测到存在依赖数据，不能删除!`; // 提示信息
        break; // 找到一个无法删除的商品，停止检查
      }
    } else {
      ElMessage.error('查询商品引用状态失败，请重试。');
      return;
    }
  }

  // 提示用户
  if (!canDelete) {
    ElMessage.warning(message); // 如果有商品无法删除，提示用户
    return; // 无法删除，返回
  }

  // 提示用户确认删除
  ElMessageBox.confirm('此操作将永久删除所选商品，是否继续?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 批量删除
    try {
      await reqeust.delete("/commodity/material/delete", {
        data: ids // 传入要删除的商品 ID 列表
      });

      ElMessage.success('批量删除成功！'); // 提示用户删除成功
      loadMenus(); // 重新加载数据
    } catch (error) {
      ElMessage.error('批量删除失败，请重试！'); // 提示用户删除失败
      console.error(error);
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作'); // 提示用户已取消删除
  });
};



// 查询最大条码函数
let findById = () => {
  reqeust.get("/commodity/material/max")
    .then(resp => {
      currentBarcode.value = resp.data; // 存储查询到的最大条码
    });
};
findById();
// 新增弹窗
let insert = (menu) => {
  title.value = menu.cname;
  visible.value = true;
  // 将当前条码传递给弹窗的表单
  data.value.barcode = currentBarcode.value; // 假设你的新增弹窗的表单数据中有一个属性是 
  router.push(menu.path);
  loadMenus();
}

// 编辑弹窗
let update = (menu, row) => {
  title.value = menu.cname
  visible.value = true;
  data.value = row
  router.push(menu.path)
}


//关闭弹窗
let close = () => {
  visible.value = false;
  router.push("/commodity/material")
}





// 定义列设置数组
let columns = ref([
  { label: '操作', prop: 'operation', visible: true, width: 150, align: 'center' },// 添加“操作”列
  // { label: '图片', prop: 'imgName', visible: true },
  { label: '条码', prop: 'erpMaterialExtend.barCode', visible: true, width: 150 },
  { label: '名称', prop: 'name', visible: true, width: 150 },
  { label: '规格', prop: 'standard', visible: true, width: 150 },
  { label: '型号', prop: 'model', visible: true, width: 150 },
  { label: '颜色', prop: 'color', visible: true, width: 150 },
  { label: '类别', prop: 'category.name', visible: true, width: 150 },
  { label: '扩展信息', prop: 'mfrs', visible: true, width: 150 },
  { label: '单位', prop: 'unit', visible: true, width: 150 },
  { label: '基础重量', prop: 'weight', visible: true, width: 150 },
  { label: '保质期', prop: 'expiryNum', visible: true, width: 150 },
  { label: '库存', prop: 'stock', visible: true, width: 150 },
  { label: '采购价', prop: 'erpMaterialExtend.purchaseDecimal', visible: true, width: 150 },
  { label: '零售价', prop: 'erpMaterialExtend.commodityDecimal', visible: true, width: 150 },
  { label: '销售价', prop: 'erpMaterialExtend.wholesaleDecimal', visible: true, width: 150 },
  { label: '最低售价', prop: 'erpMaterialExtend.lowDecimal', visible: true, width: 150 },
  { label: '仓库货架', prop: 'position', visible: true, width: 150 },
  { label: '备注', prop: 'remark', visible: true, width: 150 },
  { label: '状态', prop: 'enabled', visible: true, width: 100, align: 'center' }


]);
const visibleColumns = ref(columns.value.filter(col => col.visible).map(col => col.prop));

watch(visibleColumns, (newVal) => {
  console.log('改后的列：', newVal);
  columns.value.forEach(col => {
    col.visible = newVal.includes(col.prop);

    // console.log('原列' ,col.prop);
    console.log('新列', newVal.includes(col.prop));

  });

  loadMenus();
});

</script>

<style scoped></style>
